package main

import (
	"fmt"
	"log/slog"
	"logengine/api"
	"logengine/core"
	"logengine/env"
	"os"
	"runtime"
	"time"

	"github.com/icetech233/gin"
)

// "/mnt/xy/data_addr.csv"

// init init exec
func init() {
	initEnv()
	initLog()
	initDataAddr()
}

func initLog() {
	_ = os.MkdirAll("/mnt/xy/logs", 0777)
	_n := time.Now()

	fileName := fmt.Sprintf("%d%02d%02d", _n.Year(), _n.Month(), _n.Day())
	logFile, err := os.OpenFile("/mnt/xy/logs/web_"+fileName+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
	if err != nil {
		panic(err)
	}
	// io.MultiWriter()
	newLogger := slog.New(slog.NewTextHandler(logFile, nil))
	slog.SetDefault(newLogger)

}

var isLoadDataAddrCsv bool = false

func initDataAddr() {
	if !isLoadDataAddrCsv {
		return
	}

	csvPath := "/mnt/xy/data_addr.csv"
	csvData, err := os.ReadFile(csvPath)
	if err != nil {
		slog.Error("无法加载配置文件:" + csvPath)
		if runtime.GOOS == "linux" {
			panic(err)
		}
		return
	}
	core.InitDataAddrTree(csvData)
}

func initEnv() {
	env.InitReadEnv()
}

func main() {
	// 开启 消息队列 用来分割数据
	go core.StartMQ()
	// 路由
	ginStart()
}

func ginStart() {
	gin.SetMode(gin.ReleaseMode)
	engine := gin.New()
	api.InitRouterV1(engine)
	engine.Run(":9009")
}
